#include "Resignature.h"
#include "ui_Resignature.h"
#include "Mainpage.h"

#include <QMessageBox>
#include <QDateTime>

#include <QBitmap>
#include <QStyleOption>

#include "mymessagebox.h"

Resignature::Resignature(const QString &id, Mainpage *mainpage, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Resignature)
    , mainpageWindow(mainpage)
    , employeeId(id)  // 通过构造函数传递工号
    , tcpSocket(new QTcpSocket(this))  // 初始化 TCP 套接字
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    connect(tcpSocket, &QTcpSocket::readyRead, this, &Resignature::readServerResponse);

    // 发送工号到服务器
    sendEmployeeIdToServer();

    // 当用户选择考勤组时
    connect(ui->group, &QComboBox::currentTextChanged, this, &Resignature::onGroupSelected);
}

Resignature::~Resignature()
{
    delete ui;
}

// 实现窗口拖动功能
void Resignature::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Resignature::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Resignature::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Resignature::on_returnButton_clicked()
{
    this->close();
    mainpageWindow->show();
}

void Resignature::on_yes_clicked()
{
    // 获取输入内容
    QString selectedGroup = ui->group->currentText();
    QString selectedDate = ui->date->currentText();
    QString reason = ui->reason->toPlainText();

    if (selectedGroup.isEmpty() || selectedDate.isEmpty() || reason.isEmpty()) {
        // QMessageBox::warning(this, "错误", "请完善相应信息");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("请完善相应信息");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 构建提交的数据
    QString data = QString("SUBMIT|%1|%2|%3|%4").arg(employeeId).arg(selectedGroup).arg(selectedDate).arg(reason);

    // 发送数据到服务器
    tcpSocket->write(data.toUtf8());
}

void Resignature::sendEmployeeIdToServer()
{
    // 连接到服务器
    tcpSocket->connectToHost("127.0.0.1", 12352);
    if (tcpSocket->waitForConnected(3000)) {
        QString request = QString("GET_GROUPS|%1").arg(employeeId);
        tcpSocket->write(request.toUtf8());
    } else {
        // QMessageBox::warning(this, "连接失败", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("连接失败");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Resignature::onGroupSelected(const QString &groupId)
{
    // 当选择考勤组时发送请求获取旷工日期
    sendGroupIdToServer(groupId);
}

void Resignature::sendGroupIdToServer(const QString &groupId)
{
    QString request = QString("GET_DATES|%1|%2").arg(employeeId).arg(groupId);
    tcpSocket->write(request.toUtf8());
}

void Resignature::readServerResponse()
{
    QByteArray data = tcpSocket->readAll();
    QString response = QString::fromUtf8(data);

    QStringList parts = response.split("|");
    QString responseType = parts[0];

    if (responseType == "GROUPS") {
        ui->group->clear();
        if (parts[1] == "NO_GROUP") {
            ui->group->addItem("未有考勤组");
        } else {
            for (int i = 1; i < parts.size(); ++i) {
                ui->group->addItem(parts[i]);
            }
        }
    } else if (responseType == "DATES") {
        ui->date->clear();
        if (parts[1] == "NO_DATES") {
            ui->date->addItem("未有旷工");
        } else {
            for (int i = 1; i < parts.size(); ++i) {
                ui->date->addItem(parts[i]);
            }
        }
    } else if (responseType == "SUBMIT_SUCCESS") {
        // QMessageBox::information(this, "成功", "申请成功");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("成功");
        msgBox.setText("申请成功");
        msgBox.setButton("确定");
        msgBox.exec();
        ui->reason->clear();
    }
}
